<?php
class base {
	private $kv;
	private $config;
	public function __construct () {
		$this->init();
	}
	public function init () {
		$this->kv=new SaeKV();
		$this->kv->init();
	}
	public function db ($type,$key,$val='',$is_json=TRUE) {
		if ($type=='get') {
			if ($is_json) return jd($this->kv->get(DBPRE.$key));
			else return $this->kv->get(DBPRE.$key);
		} elseif ($type=='set') {
			if ($is_json && is_array($val)) return $this->kv->set(DBPRE.$key,json_encode($val));
			else return $this->kv->set(DBPRE.$key,$val);
		}
	}
	public function init_config ($re=FALSE) {
		if (is_array($this->config) && !$re) return;
		$cfg=$this->db('get','config');
		if (!is_array($cfg)) $cfg=array();
		$this->config=$cfg;
	}
	public function getval ($name) {
		$this->init_config();
		if (isset($this->config[$name])) return $this->config[$name];
		else return NULL;
	}
	public function setval ($name,$val) {
		$this->init_config();
		$this->config[$name]=$val;
		$this->db('set','config',$this->config);
	}
	public function get_tbs (){
		static $tbs='';
		if (!empty($tbs)) return $tbs;
		$tbs_json=curl_get('http://tieba.baidu.com/dc/common/tbs');
		$tbsaaa=jd($tbs_json);
		$tbs=$tbsaaa['tbs'];
		return $tbs;
	}
	function get_cookie () {
		static $cookie='';
		if (!empty($cookie)) return $cookie;
		$cookie=$this->getval('cookie');
		return $cookie;
	}
	public function get_fid ($tieba) {
		$url=$this->mkurl('f?kw='.$tieba);
		$contents=curl_get($url,'',2);
		$fid=0;
		$reg='/PageData.forum([ ]*)=([ ]*){(.*?)"forum_id":(\d+)/';
		preg_match_all($reg,$contents,$fids);
		$fid=$fids[4][0];
		if ($fid==0) $this->DisplayError('无法获取该贴吧的fid');
		return $fid;
	}
	public function is_login (){
		$url='http://tieba.baidu.com/dc/common/tbs';
		$check=jd(curl_get($url));
		if ($check['is_login']!=1) return FALSE;
		else return TRUE;
	}
	public function ShowTips ($info,$type) {
		if (defined('CRON')) exit('CRON');
		include(TPL.'head.html');
		echo '<div class="alert alert-',$type,'">',$info,'</div>';
		include(TPL.'footer.html');
	}
	public function mkurl ($dir,$qian='') {
		$tburl='tieba.baidu.com';
		$r='http://';
		if (!empty($qian)) $r.=$qian.'.';
		$r.=$tburl.'/'.$dir;
		return $r;
	}
	public function DisplayError ($info) {
		$this->ShowTips($info,'danger');
		exit;
	}
	public function get_bduss () {
		$cookie=trim($this->get_cookie());
		if (strpos($cookie,'BDUSS=')===FALSE) $this->DisplayError('找不到BDUSS');
		if (preg_match('/BDUSS=(.*?);/',$cookie,$matches)) {
			$BDUSS=trim($matches[1]);
		} elseif (preg_match('/BDUSS=(.*?)$/',$cookie,$matches)) {
			$BDUSS=trim($matches[1]);
		} else {
			$this->DisplayError('找不到BDUSS');
		}
		return $BDUSS;
	}
}
?>